import adminApi from '@/api/adminApi'
import { getToken, setToken, removeToken, setUserInfo, getUserInfo } from '@/utils/auth'
import { MessageBox, Message } from 'element-ui'
// import { resetRouter } from '@/router'
import Cookies from 'js-cookie'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    routerHis: [],
    fieldList: {}
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  CLEAR_ROUTES: (state) => {
    state.permission = {
      routes: [],
      addRoutes: [],
      oldRoutes: []
    }
  },
  SET_ROUTER_HIS: (state, routerHis) => {
    state.routerHis = routerHis
  },
  // 设置字段权限
  SET_fieldList: (state, fieldList) => {
    state.fieldList = fieldList
  },
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password, verification } = userInfo
    let base_64_pwd = window.btoa(username + ':' + password);
    localStorage.setItem('user_login', base_64_pwd)
    return new Promise((resolve, reject) => {
      adminApi.authentication({
        sms_code: verification
      }).then(response => {
        const { data } = response
        console.log(response, "登录 store")
        if (response.code == '200') {
          let userInfo = {
            avatar: data.image_url,
            nickName: data.user_name,
            cityName: data.area,
            phone: data.user_phone,
            userid: data.user_uuid,
            role_id: data.role_id,
            position: data.position,
            position_id: data.position_id,
            loginTime: Date.parse(new Date()) / 1000,
            discount_ratio: data.discount_ratio,
            settlement_discount_ratio: data.settlement_discount_ratio
          }
          setUserInfo(userInfo);
          commit('SET_TOKEN', data.token);
          commit('SET_ROUTER_HIS', [])
          setToken(data.token);
          resolve(response);
        } else {
          Message({
            type: 'warning',
            message: response.message
          })
          reject(response);
        }
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 用户字段权限
  getOrganizationDetails({ commit }, data) {
    adminApi
      .getOrganizationDetails({
        id: getUserInfo().position_id,
      })
      .then((res) => {
        // console.log(res.data, "字段权限");
        let field_permissions = res.data[0].field_permissions
          ? JSON.parse(res.data[0].field_permissions)
          : "";
        if (!res.data[0].field_permissions) return;
        console.log(field_permissions, "所有字段权限");
        commit('SET_fieldList', field_permissions);
      });
  },


  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve();
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  },
  // router his
  setRouter({ commit }, routerHis) {
    // console.log(state.routerHis, "添加", routerHis)
    let hisArr = state.routerHis;
    return new Promise(resolve => {
      let index = hisArr.findIndex(item => {
        return item.name == routerHis.name;
      })
      if (index == -1) {
        hisArr.push(routerHis)
      } else {
        hisArr.splice(index, 1, routerHis);
      }
      commit('SET_ROUTER_HIS', hisArr)
      resolve()
    })
  },
  // router del
  delRouter({ commit }, routerHis) {
    // console.log(routerHis, "删除")
    let hisArr = state.routerHis;
    return new Promise(resolve => {
      let index = hisArr.findIndex(item => {
        return item.name == routerHis.name;
      })
      if (index != -1) {
        hisArr.splice(index, 1);
      }
      // console.log(hisArr, "hisArr---------------------")
      commit('SET_ROUTER_HIS', hisArr)
      resolve(hisArr)
    })
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

